import { nextTick, ref } from 'vue';
import { Button, Input, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { useAuthStore } from '@/store/modules/auth';
import { isNonNegativeInteger } from '@/utils';
import { downLoadExcel } from '@/service/api/api';
import ViewStandard from '../../modal/view-standard.vue';

const authStore = useAuthStore();
const lotids = ref([]);

const lotType = ref('searchInput');
const pageRef = ref(null);
let topFormModel;
let bottomFormModel;
let formTableData;
let modelOperateType = 'add';
const fileList = ref([]);

const modalVisible = ref(false);

export default {
  url: '/qms/electricalTest/singleTestProd/list',
  addUrl: '/qms/electricalTest/singleTestProd/add',
  editUrl: '/qms/electricalTest/singleTestProd/update',
  delUrl: '/qms/electricalTest/singleTestProd/deleteBatch',
  renderComponents: {},
  getPageRef(mainPageRef) {
    pageRef.value = mainPageRef;
  },
  searchFormList: [
    {
      type: 'input',
      key: 'moduleNo',
      label: '生产型号',
      placeholder: '请输入生产型号',
      span: 24,
      md: 12,
      lg: 8,
      xl: 8,
      xxl: 4
    },
    {
      type: 'input',
      key: 'lotId',
      label: 'LOT号',
      placeholder: '请输入LOT号',
      span: 24,
      md: 12,
      lg: 8,
      xl: 8,
      xxl: 4
    },
    {
      type: 'input',
      key: 'serialNum',
      label: '单据号',
      placeholder: '请输入单据号',
      span: 24,
      md: 12,
      lg: 8,
      xl: 8,
      xxl: 4
    },
    {
      type: 'select',
      key: 'state',
      label: '审核状态',
      placeholder: '请选择审核状态',
      span: 24,
      md: 12,
      lg: 8,
      xl: 8,
      xxl: 4,
      selectOptions: [
        {
          value: '0',
          label: '待领班审核'
        },
        {
          value: '1',
          label: '待修改'
        },
        {
          value: '2',
          label: '待主管审核'
        },
        {
          value: '3',
          label: '审核完成'
        }
      ]
    },
    {
      type: 'dateRangePicker',
      key: 'time',
      label: '时间',
      valueFormat: 'YYYY-MM-DD',
      span: 24,
      md: 12,
      lg: 10,
      xl: 8,
      xxl: 6
    }
  ],
  column: [
    {
      key: 'dataIndex',
      dataIndex: 'dataIndex',
      title: '序号',
      width: 70,
      fixed: 'left',
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'moduleNo',
      dataIndex: 'moduleNo',
      title: '生产型号',
      width: 150,
      align: 'center',
      fixed: 'left',
      checked: true,
      ellipsis: true
    },
    {
      key: 'lotId',
      dataIndex: 'lotId',
      title: 'LOT号',
      width: 150,
      align: 'center',
      fixed: 'left',
      checked: true,
      ellipsis: true
    },
    {
      key: 'serialNum',
      dataIndex: 'serialNum',
      title: '单据号',
      width: 130,
      align: 'center',
      fixed: 'left',
      checked: true,
      ellipsis: true
    },
    {
      key: 'state',
      dataIndex: 'state',
      title: '状态',
      width: 120,
      align: 'center',
      checked: true,
      ellipsis: true,
      customRender: ({ record }) => {
        return ['待领班审核', '待修改', '待主管审核', '审核完成'][record.state];
      }
    },
    {
      key: 'modifyTime',
      dataIndex: 'modifyTime',
      title: '时间',
      width: 180,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'weekNo',
      dataIndex: 'weekNo',
      title: '周期',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'totalCheckNum',
      dataIndex: 'totalCheckNum',
      title: '总测试数(set)',
      width: 130,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'machineNo',
      dataIndex: 'machineNo',
      title: '设备编号',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'ngNum',
      dataIndex: 'ngNum',
      title: '不良数(set)',
      width: 120,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'ngRate',
      dataIndex: 'ngRate',
      title: '不良率',
      width: 120,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'repairBoardRetestNum',
      dataIndex: 'repairBoardRetestNum',
      title: '修理板复测数量(set)',
      width: 150,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'testItem1',
      dataIndex: 'testItem1',
      title: '测试电压',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'testItem2',
      dataIndex: 'testItem2',
      title: '导通阻值',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'testItem3',
      dataIndex: 'testItem3',
      title: '绝缘阻值',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'testItem3',
      dataIndex: 'testItem3',
      title: '绝缘阻值',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'checkType1',
      dataIndex: 'checkType1',
      title: '首件检查',
      width: 90,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'checkType2',
      dataIndex: 'checkType2',
      title: '自主检查',
      width: 90,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'checkType3',
      dataIndex: 'checkType3',
      title: '末件检查',
      width: 90,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'shiftType',
      dataIndex: 'shiftType',
      title: '班别',
      width: 120,
      align: 'center',
      checked: true,
      ellipsis: true,
      customRender: ({ record }) => {
        return ['白班', '夜班'][record.shiftType];
      }
    },
    {
      key: 'selfCheckFrequency',
      dataIndex: 'selfCheckFrequency',
      title: '自检频率',
      width: 140,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'operator',
      dataIndex: 'operator',
      title: '操作员',
      width: 140,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'foreman',
      dataIndex: 'foreman',
      title: '领班审核',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'foremanTime',
      dataIndex: 'foremanTime',
      title: '领班审核时间',
      width: 180,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'examiner',
      dataIndex: 'examiner',
      title: '主管审核',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'examinerTime',
      dataIndex: 'examinerTime',
      title: '主管审核时间',
      width: 180,
      align: 'center',
      checked: true,
      ellipsis: true
    },

    {
      key: 'remark',
      dataIndex: 'remark',
      title: '备注',
      width: 180,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'createTime',
      dataIndex: 'createTime',
      title: '创建时间',
      width: 180,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'updateTime',
      dataIndex: 'updateTime',
      title: '修改时间',
      width: 180,
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'updateBy',
      dataIndex: 'updateBy',
      title: '修改人',
      width: 100,
      align: 'center',
      checked: true,
      ellipsis: true
    }
  ],
  searchParam: ref({
    moduleNo: null,
    lotId: null,
    state: null,
    time: null
  }),
  rednderComponents: [
    () => <ViewStandard visible={modalVisible.value} onClose={() => (modalVisible.value = false)}></ViewStandard>
  ],
  scroll: { x: 2500, y: 'auto' },
  formId: '83',
  otherBtnList: [
    {
      icon: 'icon-chakanbiaozhun',
      name: '查看标准',
      iconType: 3,
      auth: 'test-production-record-sheet:lookStandard',
      handleClick(item, tableSelect, searchParams) {
        modalVisible.value = true;
      }
    },
    {
      icon: 'icon-ic-round-download ',
      name: '导出不良',
      iconType: 3,
      auth: 'test-production-record-sheet:downloadBadness',
      handleClick: () => {
        downLoadExcel(
          `/qms/electricalTest/singleTestProd/exportExcel`,
          {},
          `导出不良${dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`
        );
      }
    },
    {
      icon: 'icon-ic-round-upload ',
      name: '导入不良',
      iconType: 3,
      isUpload: true,
      auth: 'test-production-record-sheet:uploadBadness',
      url: '/electricalTest/singleTestProd/importExcel',
      fileList: fileList.value,
      handleChange(info) {
        if (info.file.status === 'done') {
          message.success('导入不良成功!');
          fileList.value = [];
        } else if (info.file.status === 'error') {
          message.error(`导入不良失败`);
          fileList.value = [];
        }
      }
    }
  ],
  topFormList: [
    // 用于获取model
    {
      type: 'getModel',
      hidden: true,
      handle(topModel, bottomModel, tableData, operateType) {
        topFormModel = topModel;
        bottomFormModel = bottomModel;
        formTableData = tableData;
        modelOperateType = operateType;
      }
    },

    {
      type: 'searchInput',
      key: 'moduleNo',
      label: '生产型号',
      span: 12,
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      disabled: false,
      rule: {
        required: true,
        message: '请输入生产型号',
        trigger: 'change'
      },
      transfromSearch(model, searchData) {
        topFormModel = model;
        lotids.value = searchData.lotNo.map(item => {
          return {
            // label: `${item.techName} - ${item.lotNo}`,
            label: `${item.lotNo}`,
            value: `${item.lotNo}`
          };
        });
        lotType.value = 'select';
        model.value.lotId = null;
        Object.keys(model.value).forEach(item => {
          model.value[item] = searchData[item] || model.value[item];
        });
        if (Number(searchData.ngNum) === 0) {
          topFormModel.value.ngNum = null;
        }
      }
    },
    {
      type: lotType,
      key: 'lotId',
      label: 'Lot号',
      searchKey: 'lotNumber',
      rule: {
        required: true,
        message: '请输入Lot号',
        trigger: 'change'
      },
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      span: 12,
      selectOptions: lotids,
      transfromSearch(model, searchData) {
        topFormModel = model;
        Object.keys(model.value).forEach(item => {
          model.value[item] = searchData[item] || model.value[item];
        });
        if (Number(searchData.ngNum) === 0) {
          topFormModel.value.ngNum = null;
        }
      }
    },
    {
      type: 'datePicker',
      key: 'modifyTime',
      label: '录入时间',
      span: 8,
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      showTime: true,
      rule: {
        required: true,
        message: '请选择录入时间',
        trigger: 'change'
      }
    },
    {
      type: 'input',
      key: 'totalCheckNum',
      label: '总测试数',
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      rule: {
        required: true,
        message: '请填写总测试数',
        trigger: 'change'
      },
      span: 8,
      change(e, val, formVal) {
        console.log('e :>> ', e);
        // if (topFormModel.value.totalCheckNum == '0') {
        //   topFormModel.value.totalCheckNum = null;
        //   topFormModel.value.ngRate = null;
        //   return;
        // }
        if (topFormModel.value.totalCheckNum !== null || topFormModel.value.totalCheckNum !== undefined) {
          // formVal.ngRate = `${((val / formVal.totalCheckNum) * 100).toFixed(3)}%`;
          topFormModel.value.ngRate = `${((topFormModel.value.ngNum / val) * 100).toFixed(3)}%`;
        }
      }
    },
    {
      type: 'input',
      key: 'ngNum',
      label: '不良数',
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      rule: {
        required: true,
        message: '请输入不良数',
        trigger: 'change'
      },
      span: 8,
      change(e, val, formVal) {
        console.log('e :>> ', e);
        if (formVal.totalCheckNum) {
          formVal.ngRate = `${((val / formVal.totalCheckNum) * 100).toFixed(3)}%`;
        }
      }
    },
    {
      type: 'input',
      key: 'machineNo',
      label: '设备编号',
      span: 8,
      rule: {
        required: true,
        message: '请填写设备编号',
        trigger: 'change'
      }
    },
    {
      type: 'input',
      key: 'ngRate',
      label: '不良率',
      disabled: true,
      span: 8
    },
    {
      type: 'input',
      key: 'testItem1',
      label: '测试电压',
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      span: 8,
      rule: {
        required: true,
        message: '请填写测试电压',
        trigger: 'change'
      }
    },
    {
      type: 'select',
      key: 'testItem2',
      label: '导通阻值',
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      span: 8,
      selectOptions: [
        {
          value: '10Ω',
          label: '10Ω'
        },
        {
          value: '20Ω',
          label: '20Ω'
        },
        {
          value: '30Ω',
          label: '30Ω'
        },
        {
          value: '50Ω',
          label: '50Ω'
        }
      ]
    },
    {
      type: 'select',
      key: 'testItem3',
      label: '绝缘阻值',
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      span: 8,
      selectOptions: [
        {
          value: '10MΩ',
          label: '10MΩ'
        },
        {
          value: '20MΩ',
          label: '20MΩ'
        },
        {
          value: '30MΩ',
          label: '30MΩ'
        },
        {
          value: '50MΩ',
          label: '50MΩ'
        }
      ]
    },
    {
      type: 'input',
      key: 'weekNo',
      label: '周期',
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      span: 8,
      rule: {
        required: true,
        message: '请填写周期',
        trigger: 'change'
      }
    },
    {
      type: 'input',
      key: 'repairBoardRetestNum',
      label: '修理板复测数量(set)',
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      span: 8,
      rule: {
        required: true,
        message: '请填写修理板复测数量',
        trigger: 'change'
      }
    },
    {
      type: 'radio',
      key: 'shiftType',
      label: '班别',
      span: 12,
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      defaultValue: '0',
      selectOptions: [
        {
          label: '白班',
          value: '0'
        },
        {
          label: '夜班',
          value: '1'
        }
      ]
    },

    {
      type: 'radio',
      key: 'checkType1',
      label: '首件检查',
      span: 8,
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },

      showReset: true,
      selectOptions: [
        {
          label: 'OK',
          value: 'OK'
        },
        {
          label: 'NG',
          value: 'NG'
        }
      ]
    },

    {
      type: 'radio',
      key: 'checkType2',
      label: '自主检查',
      span: 8,
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },

      showReset: true,
      selectOptions: [
        {
          label: 'OK',
          value: 'OK'
        },
        {
          label: 'NG',
          value: 'NG'
        }
      ]
    },

    {
      type: 'radio',
      key: 'checkType3',
      label: '末件检查',
      span: 8,
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      showReset: true,

      showReset: true,
      selectOptions: [
        {
          label: 'OK',
          value: 'OK'
        },
        {
          label: 'NG',
          value: 'NG'
        }
      ]
    },

    {
      type: 'input',
      key: 'checkNum1',
      label: '首件检查数量',
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      span: 8
    },
    {
      type: 'input',
      key: 'checkNum2',
      label: '自主检查数量',
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      span: 8
    },
    {
      type: 'input',
      key: 'checkNum3',
      label: '末件检查数量',
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      span: 8
    },
    {
      type: 'textarea',
      key: 'remark',
      label: '备注',
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      textareaRows: 1,
      span: 24
    }
    // {
    //   type: 'input',
    //   key: 'selfCheckFrequency',
    //   label: '自检频率',
    //   placeholder: '请输入自检频率',
    //   tansfromDisabled(operateType) {
    //     return operateType === 'look';
    //   },
    //   span: 8
    // }
  ],
  bottomList: [
    {
      type: 'input',
      key: 'operator',
      label: '操作员',
      defaultValue: authStore.userInfo.user.nickName || authStore.userInfo.user.userName,
      tansfromDisabled(operateType) {
        return operateType === 'look';
      },
      span: 8
    },
    {
      type: 'input',
      key: 'foreman',
      label: '领班审核',

      disabled: true,
      span: 8
    },
    {
      type: 'input',
      key: 'examiner',
      label: '主管审核',
      disabled: true,
      span: 8
    }
  ],
  editMethod: 'put',
  modalGetTableDataUrl: '/qms/electricalTest/singleTestProd/',
  modalTableKey: 'badId',
  modalHeight: '97vh',
  modalAddTableKey: 'badDoList',
  modalTableColumn: [
    {
      key: 'index',
      dataIndex: 'index',
      title: '序号',
      width: 70,
      fixed: 'left',
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'badName',
      dataIndex: 'badName',
      title: '检验项目',
      align: 'center',
      checked: true,
      ellipsis: true
    },
    {
      key: 'number',
      dataIndex: 'number',
      title: '缺陷数量',
      align: 'center',
      checked: true,
      ellipsis: true,
      customRender: ({ record }) => {
        if (record.disabled) {
          return <div style="min-width:150px">{record.number}</div>;
        }
        return (
          <Input
            style="height: 22px !important;"
            value={record.number}
            onChange={e => {
              record.number = e.target.value;
              if (!topFormModel) return;
              let sum = 0;
              topFormModel.value.ngNum = 0;
              const modalTableData = pageRef.value.value.getModalTableData();

              for (let i = 0; i < modalTableData.length; i++) {
                sum += Number.parseInt(modalTableData[i].number, 10) || 0;
              }
              topFormModel.value.ngNum = sum;
              topFormModel.value.ngRate = `${((topFormModel.value.ngNum / topFormModel.value.totalCheckNum) * 100).toFixed(3)}%`;
            }}
            onBlur={e => {
              const value = e.target.value;
              if (!(isNonNegativeInteger(Number(value).toString()) && Number(value >= 0))) {
                message.error('请输入正整数');
                record.number = null;
                return;
              }
              record.number = Number(value);
            }}
          ></Input>
        );
      }
    },
    {
      key: 'badName',
      dataIndex: 'badName',
      title: '操作',
      align: 'center',
      checked: true,
      ellipsis: true,
      width: 100,
      customRender: row => {
        if (modelOperateType === 'look') {
          return '';
        }
        return (
          <Button
            type="link"
            onClick={() => {
              pageRef.value.value.delModalTableRow(row.record);
            }}
          >
            删除
          </Button>
        );
      }
    }
  ],
  modalClose() {
    lotType.value = 'searchInput';
  },
  modleSearchUrlObj: {
    lotId: '/rcerp/agv/erp/findByLotNo',
    moduleNo: '/rcerp/agv/erp/findByModuleNo'
  },
  modalGetTableUrlSuffix: {
    add: 'selectBadId',
    byId: 'listBad'
  },
  addUseRowData: true,
  // 点击新增openModal循环本条数据--方便用户直接修改
  openModal(val) {
    console.log(val);
    if (val.operateType === 'add' && val.currentRow) {
      nextTick(() => {
        Object.keys(topFormModel.value).forEach(key => {
          topFormModel.value[key] = val.currentRow[key];
        });
        topFormModel.value.modifyTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
        // console.log(topFormModel.value);
      });
    }
  }
};
